package org.turnlink.sclm.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.turnlink.sclm.model.ContactList;
import org.turnlink.sclm.service.ContactListManager;
import org.turnlink.sclm.utils.InvalidSessionException;

@Controller
@RequestMapping("/list/{token}")
public class ContactListServiceController extends AbstractServiceController {

	@SuppressWarnings("unused")
	@Autowired
	private ContactListManager contactListManager;

	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public ModelAndView create(@PathVariable String token,
			ContactList contactListMap, HttpServletResponse response) {
		checkSession(token, response);
		this.contactListManager.create(contactListMap);
		return null;
	}

	@RequestMapping(value = "/addConcats", method = RequestMethod.GET)
	public ModelAndView addContacts(@PathVariable String token, @RequestParam Integer accountId,
			@RequestParam String contactListName, @RequestParam List<Integer> contactIds, HttpServletResponse response) {
		this.contactListManager.addContactsToList(accountId, contactListName, contactIds);
		checkSession(token, response);
		return null;
	}
	
	@RequestMapping(value = "/removeContacts", method = RequestMethod.GET)
	public ModelAndView removeContacts(@PathVariable String token, @RequestParam Integer accountId,
			@RequestParam String contactListName, @RequestParam List<Integer> contactIds, HttpServletResponse response) {
		checkSession(token, response);
		this.contactListManager.removeContactsFromList(accountId, contactListName, contactIds);
		return null;
	}

	@RequestMapping(value = "/remove", method = RequestMethod.GET)
	public ModelAndView remove(@PathVariable String token, @RequestParam Integer accountId,
			@RequestParam String contactListName, HttpServletResponse response) {
		checkSession(token, response);
		this.contactListManager.remove(accountId, contactListName);
		return null;
	}
	
	@ExceptionHandler(InvalidSessionException.class)
	public String handleInvalidSessionException(InvalidSessionException ex, HttpServletResponse response) throws IOException {
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
		return null;
	}
	
}
